﻿<%@ Page Title="" Language="C#" MasterPageFile="~/SIPO.master" AutoEventWireup="false"
    CodeFile="recInvoicelist.aspx.cs" Inherits="SIPO.Web.Lists.Administration.Catalog.recInvoicelist" %>

<asp:Content ID="ctnBody" ContentPlaceHolderID="body" runat="server">

     <link type="text/css" rel="stylesheet" href="<%= ResolveUrl("~/styles/ui.jqgrid.css") %>" />
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/i18n/grid.locale-id.js") %>"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
    <script src="<%= ResolveUrl("~/scripts/helper.js") %>" type="text/javascript"></script>
    <div>
        <button id="btnSave" type="button" onclick="OpenForm('save');">
             Cetak Surat Setoran</button>
        <button id="btnEdit" type="button" onclick="OpenFormedit();">
            Ubah</button>      
    </div>
    <br />
    <br />
    <table id="table" class="scroll" cellpadding="0" cellspacing="0">
    </table>
    <div id="pager" class="scroll">
    </div>
    <br />
    <div id="dialog" title="Default dialog">
    </div>
    <script type="text/javascript">

        $("#btnSave").button({ icons: { primary: "ui-icon-disk"} });
        $("#btnEdit").button({ icons: { primary: "ui-icon-pencil"} });
        
        
    </script>
    <script type="text/javascript">

        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Transaction/recBillinghandler.ashx") %>';

        $('#table').jqGrid({
            url: handlerUrl + '?method=getdatainvoice',
            datatype: 'json',

            colNames: ['ID','PrevBillingNo', 'Sektor', 'Sub Sektor','Perusahaan', 'Jenis Tagihan','Kode Tagihan','ID Tagihan', 'Keterangan', 'Jatuh Tempo', 'Nilai Tagihan (Rp)' ,'No Invoice','No. Surat Setoran','Sub Sub Sektor', 'SubSubSectorID', 'SectorCode', 'SubSectorCode','IsManual','IsHold','IsIsRestructur'],

            colModel: [
                    { name: 'BillingNo', hidden: false, index: 'BillingNo', width: 150 },
                    { name: 'PrevBillingNo', hidden: true, index: 'PrevBillingNo', width: 150 },
                    { name: 'recDebtorSector.recSector.SectorName', hidden: true, index: 'SectorName', width: 150, searchoptions: { searchhidden: true} },
                    { name: 'recDebtorSector.recSubSector.SubSectorName', hidden: true, index: 'SubSectorName', width: 150, searchoptions: { searchhidden: true} },
                    { name: 'recDebtorSector.recDebtor.DebtorName', index: 'DebtorName', width: 200, searchoptions: { sopt: ['eq', 'cn']} },
                    { name: 'recTransactionType.TransTypeName', index: 'TransTypeName', width: 100, searchoptions: { sopt: ['eq', 'cn']} },
                    { name: 'recTransactionType.TransTypeCode',hidden: true, index: 'TransTypeCode', width: 100, searchoptions: { sopt: ['eq', 'cn']} },
                    { name: 'recTransactionType.TransTypeID', hidden: true,index: 'TransTypeID', width: 100, searchoptions: { sopt: ['eq', 'cn']} },
                    { name: 'ForPayment', index: 'ForPayment', align: 'left', width: 200, searchoptions: { sopt: ['eq', 'cn']} },
                    { name: 'DueDate', index: 'DueDate', align: 'center', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, formatter: 'date', formatoptions: { newformat: 'd M Y'} },
                    { name: 'Value', index: 'Value', formatter: 'number', align: 'right',  width: 150, searchoptions: { sopt: ['eq', 'cn']} },
                    { name: 'InvoiceNo', hidden: true, align: 'center', index: 'InvoiceNo', width: 100 },
                    { name: 'InvoiceNo', index: 'InvoiceNo', align: 'center', formatter: returnMyLink, width: 100 },
                    
                     { name: 'recDebtorSector.recSubSubSector.SubSubSectorName', hidden: false, index: 'SubSubSectorName', width: 150 }
                    , { name: 'recDebtorSector.recSubSubSector.SubSubSectorID', hidden: true, index: 'SubSubSectorID', align: 'center', width: 100 }
                    , { name: 'recDebtorSector.recSector.SectorCode', hidden: true, index: 'SectorCode', align: 'center', width: 100 }
                    , { name: 'recDebtorSector.recSubSector.SubSectorCode', hidden: true, index: 'SubSectorCode', align: 'center', width: 100 }
                    , { name: 'IsManual', hidden: true, index: 'IsManual', width: 100 }
                    ,{ name: 'IsHold', hidden: true, align: 'center', index: 'IsHold', width: 100 }
                    ,{ name: 'IsRestructur', hidden: true, align: 'center', index: 'IsRestructur', width: 100 }
           	],
            rowNum: 10,
            id: 'DueDate',
            multiselect: true,
            rowList: [5, 10, 15, 20],
            pager: '#pager',
            sortname: 'DueDate',
            sortorder: "asc",
            viewrecords: true,
            jsonReader: { repeatitems: false },
            width: 1250,
            height: '100%',
            caption: 'Tagihan',
            ajaxGridOptions: { cache: false }
         
        });

        $("#table").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, searchtext: 'Search', refreshtext: 'Refresh' },
        {}, {}, {}, { closeOnEscape: true, multipleSearch: true, closeAfterSearch: true });

        showhidecoloumn();

        function OpenFormedit() {
            var formUrl = '<%= ResolveUrl("~/forms/transaction/recInvoiceManualEditform.aspx") %>';

            var grid = $('#table');
            var selIds = grid.jqGrid('getGridParam', 'selarrrow'),
                selText = [];
            selIsMan = [];
            selInvoice = [];
            $.each(selIds, function () {
                selText.push(grid.jqGrid('getCell', this, 'BillingNo'));
                selIsMan.push(grid.jqGrid('getCell', this, 'IsManual'));
                selInvoice.push(grid.jqGrid('getCell', this, 'InvoiceNo'));
            });
           
              
                if (selIds.length == 0) {
                    alert('Pilih data yang mau di ubah !');
                }
                else if (selIds.length > 1) {
                    alert('Pilih satu record untuk ubah data !');
                }
                else if (selIsMan == 'true' && selInvoice=='') {
                    $('#dialog').load(formUrl + '?id=' + selText + '&menuId=' + '<%= base.MenuID %>').dialog({ autoOpen: false, modal: true, width: 420, title: 'Ubah Tagihan' });
                    $('#dialog').dialog('open');
                }
                else {
                    alert('Tagihan yang dipilih tidak bisa di edit !');
                }
            
        }

        function returnMyLink(cellValue, options, rowdata) {
            var InvoiceNo = encodeURIComponent(cellValue);
            return "<a style='font-style:italic;color:Blue;text-decoration:underline' href=\"" + "#" + "\"" + " onclick=\"" + "popupform('" + InvoiceNo + "')" + "\"" + ">" + InvoiceNo + "</a>";
        }

        function popupform(cellValue) {
           
            var invoiceno = cellValue;
            if (invoiceno != "") {
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/gettransactiontype.ashx?method=getjenisinvoice") %>';
                $.ajax({
                    type: 'POST',
                    url: handlerUrl + "&invoiceno=" + invoiceno,
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (datas) {
                        $.each(datas, function (i, data) {
                            if (data.TransTypeName.toString().toLowerCase() == "registrasi") {
                                window.open('../../forms/Transaction/recPrintInvoiceform.aspx?invoiceno=' + invoiceno + "&action=registrasi", 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                            }
                            else if (data.TransTypeName.toString().toLowerCase()=="aksi korporasi") {
                                window.open('../../forms/Transaction/recPrintInvoiceform.aspx?invoiceno=' + invoiceno + "&action=aksikorporasi", 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                            }
                            else {
                                window.open('../../reports/Transaction/rptInvoice.aspx?InvoiceNo=' + invoiceno, 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                            }

                        });

                    },
                    error: function () {
                        alert('Error load jenis invoice!');
                    }
                });
            }

        }

        function OpenForm(ctl) {

            var formUrl = '<%= ResolveUrl("~/forms/transaction/recInvoiceform.aspx") %>';

            var grid = $('#table');
            var subsubsectorids = [];
            var sectorcode = "";
            var subsectorcode = "";
            var invoiceno = [];
            var totalValue = [];
            var IsHold = [];
            var IsRestructur = [];
            var jenisTagihan = [];
            var selIds = grid.jqGrid('getGridParam', 'selarrrow'),
                selText = [];
            $.each(selIds, function () {
                subsubsectorids.push(grid.jqGrid('getCell', this, 'recDebtorSector.recSubSubSector.SubSubSectorID'));
                selText.push(grid.jqGrid('getCell', this, 'BillingNo'));
                sectorcode = grid.jqGrid('getCell', this, 'recDebtorSector.recSector.SectorCode');
                subsectorcode = grid.jqGrid('getCell', this, 'recDebtorSector.recSubSector.SubSectorCode');
                invoiceno.push(grid.jqGrid('getCell', this, 'InvoiceNo'));
                totalValue.push(grid.jqGrid('getCell', this, 'Value'));
                IsRestructur.push(grid.jqGrid('getCell', this, 'IsRestructur'));
                IsHold.push(grid.jqGrid('getCell', this, 'IsHold'));
                jenisTagihan.push(grid.jqGrid('getCell', this, 'recTransactionType.TransTypeID'));

            });
            
            var status = false;
            var statusinvoice = false;

            if (ctl == 'save') {

                if (selIds.length == 0) {
                    alert('Pilih satu record untuk di cetak !');
                }
                else if (selIds.length == 1) {

                    
                    if (invoiceno == "") {
                        var yearReport = '<%= ResolveUrl("~/AjaxHandler/loaddata/getinvoice.ashx") %>';
                        $.ajax({
                            type: 'POST',
                            url: yearReport + "?method=getYearsReportYearDues&billingNo=" + selText,
                            contentType: 'application/json',
                            dataType: 'json',
                            //data: jsonData,
                            success: function (data) {

                                var result = "";
                               
                                if (data.Hasil == "True") {

                                    result = window.confirm(' Tagihan yang dipilih akan dibuatkan surat setoran, \n Namun Dasar Pengenaan anda belum update, Apakah anda yakin akan meneruskan?');
                                    //result = alert("Dasar pengenaan anda belum update,mohon update dasar pengenaan anda !");
                                }
                                else {
                                    result = window.confirm('Tagihan yang dipilih akan dibuatkan surat setoran?');
                                }

                                //result = window.confirm('Tagihan yang dipilih akan dibuatkan surat setoran?');
                                if (result) {
                                    if (parseFloat(totalValue) > 0) {
                                        simpandata(sectorcode, subsectorcode, selText);

                                    }
                                    else {
                                        alert("Data tidak bisa di simpan, pilih jumlah pembayaran yang  bernilai positif/lebih besar dari 0");
                                    }
                                }

                            },
                            error: function () {
                                alert("Error Years Report");
                            }
                        });


                    }
                    else {
                        alert("Data tidak bisa di simpan karena sudah tercetak No. Surat Setoran..");
                    }
                    //}

                }
                else {

                    var statusJenisTagihan = false;
                    //alert(jenisTagihan);
                    for (var i = 0; i < jenisTagihan.length; i = i + 1) {
                        //alert(jenisTagihan[i]);
                        if (jenisTagihan[0] != jenisTagihan[i]) {
                            statusJenisTagihan = true;
                            break;
                        }
                    }

                    if (statusJenisTagihan == true) {
                        alert("Tagihan tidak bisa dibuat surat setoran,pilih tagihan dengan jenis yang sama !");
                        return false;
                    }

                    var result = window.confirm('Tagihan yang dipilih akan dibuatkan surat setoran?');
                    if (result) {

                        for (var i = 0; i < invoiceno.length; i = i + 1) {
                            if (invoiceno[i] != "") {
                                statusinvoice = true;
                                break;
                            }

                        }

                        if (statusinvoice == false) {

                            for (var i = 0; i < subsubsectorids.length; i = i + 1) {
                                if (subsubsectorids[0] != subsubsectorids[i]) {
                                    status = true;
                                    break;
                                }
                            }

                            if (status) {
                                alert(" Simpan data tidak berhasil \n pilih tagihan dengan jenis usaha yang sama !");
                            }
                            else {
                                var total = 0;
                                for (var i = 0; i < totalValue.length; i = i + 1) {
                                    total += parseFloat(totalValue[i]);

                                }


                                if (total > 0) {

                                    simpandata(sectorcode, subsectorcode, selText);
                                }
                                else {
                                    alert("Data tidak bisa di simpan, pilih jumlah pembayaran yang  bernilai positif/ lebih besar dari 0");
                                }
                            }
                        }
                        else {
                            alert("Data tidak bisa di simpan .. \nPilih data yang belum tercetak No. Surat Setoran..");
                        }
                    }
                }
            }
            else if (ctl == 'print') {
                if (selIds.length == 0) {
                    alert('Pilih data yang mau di cetak !');
                }
                else if (selIds.length > 1) {
                    alert('Pilih satu record untuk cetak data.');
                }
                else {
                   
                    if (invoiceno != "") {
                        var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/gettransactiontype.ashx?method=getjenisinvoice") %>';
                        $.ajax({
                            type: 'POST',
                            url: handlerUrl + "&invoiceno=" + invoiceno,
                            contentType: 'application/json',
                            dataType: 'json',
                            success: function (datas) {
                                $.each(datas, function (i, data) {
                                    //if (data.TransTypeName.toString().toLowerCase() == "registrasi") {
                                    if (data.TransTypeCode == "1") {
                                        window.open('../../forms/Transaction/recPrintInvoiceform.aspx?invoiceno=' + invoiceno + "&action=registrasi", 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                                    }
                                    //else if (data.TransTypeName.toString().toLowerCase().contains("aksi korporasi")) {
                                    else if (data.TransTypeCode == "4") {
                                        window.open('../../forms/Transaction/recPrintInvoiceform.aspx?invoiceno=' + invoiceno + "&action=aksikorporasi", 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                                    }
                                    else {
                                        window.open('../../reports/Transaction/rptInvoice.aspx?InvoiceNo=' + invoiceno, 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                                    }

                                });

                            },
                            error: function () {
                                alert('Error load jenis invoice!');
                            }
                        });
                    }
                    else {
                        alert("Data tidak bisa di cetak karena No. Surat Setoran masih kosong  !");
                    }


                }
            }
         }


        function simpandata(sectorCode, subsectorCode, selText) {

            var objrecBilling = new Object();
            objrecBilling.BillingNo = encodeURIComponent(selText);
            jsonData = JSON.stringify(objrecBilling);

            var handlerUrl = '<%= ResolveUrl("~/ajaxhandler/transaction/recInvoicehandler.ashx") %>';

            $.ajax({
                type: 'POST',
                url: handlerUrl + "?method=insert&sectorCode=" + sectorCode + "&subsectorCode=" + subsectorCode,
                contentType: 'application/json',
                dataType: 'json',
                data: jsonData,
                success: function (data) {
                    if (data.IsSuccess) {
                        setTimeout("$('#table').trigger('reloadGrid');", 3000);
                        alert(data.Message);
                        window.open('../../reports/Transaction/rptInvoice.aspx?InvoiceNo=' + data.Data, 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                    }
                    else {
                        alert(data.Message);
                    }
                },
                error: function (response) {
                    var r = JSON.parse(response.responseText);
                    alert("Error Message: " + r.Message);
                }
            });

        }

        function showhidecoloumn() {
            var debtor = "<%= base.DebtorID %>";
            if (debtor == "") {
                $("#table").jqGrid('showCol', ["recDebtorSector.recDebtor.DebtorName"]);
                //$("#table").jqGrid('showCol', ["ApproveDate"]);
            }
            else {
                $("#table").jqGrid('hideCol', ["recDebtorSector.recDebtor.DebtorName"]);
                //$("#table").jqGrid('hideCol', ["ApproveDate"]);
            }

        }
    
    </script>
</asp:Content>
